<template>
  <div class="sign-in-container">
    <div class="check-in-form">
      <div class="input-group">
        <input
            type="text"
            :value="inputValue"
            @input="handleInput"
            @keyup.enter="handleSubmit"
            :disabled="isSubmitted || isSubmitting"
            maxlength="8"
            placeholder="请输入4-8位数字"
            class="input-field"
        />
        <div v-if="inputValue.length > 0 && inputValue.length < 4" class="error-message">
          至少需要输入4位数字
        </div>
        <div v-if="inputValue.length > 8" class="error-message">
          最多只能输入8位数字
        </div>
      </div>

      <button
          :disabled="!canSubmit || isSubmitting"
          @click="handleSubmit"
          class="check-in-button"
      >
        签到
      </button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import store from '@/store'
import { useRoute, useRouter } from 'vue-router'

const route = useRoute()
const router = useRouter()

// 签到码相关
const inputValue = ref('')
const isSubmitted = ref(false)
const canSubmit = ref(false)
const submitError = ref('')
const isSubmitting = ref(false)

// API配置
const api = axios.create({
  baseURL: store.getters.getBaseURL
})

// 拦截器配置
api.interceptors.request.use(config => {
  const token = sessionStorage.getItem('userToken')
  if (token) {
    config.headers.Authorization = `Bearer ${token}`
  }
  return config
})

api.interceptors.response.use(
    response => response,
    error => {
      if (error.response?.status === 401) {
        router.push('/loginAndRegister')
      }
      return Promise.reject(error)
    }
)

onMounted(() => {
  // 检查是否需要显示验证
  const isVerify = route.query.isVerify
  if (isVerify === '1' && sessionStorage.getItem(`${route.params.id}`) !== '1') {
    router.push({ path: `/verification/${isVerify}`, query: { section: route.params.id }});
  }
})

// 输入处理
const handleInput = (event) => {
  if (isSubmitted.value || isSubmitting.value) return

  // 清除非数字字符
  const cleanedValue = event.target.value.replace(/\D/g, '')
  inputValue.value = cleanedValue

  // 限制长度
  if (cleanedValue.length > 8) {
    inputValue.value = cleanedValue.slice(0, 8)
  }

  // 检查是否可以提交
  canSubmit.value = cleanedValue.length >= 4 && cleanedValue.length <= 8
}

// 提交处理
const handleSubmit = async () => {
  if (!canSubmit.value || isSubmitting.value) return

  isSubmitting.value = true
  submitError.value = ''

  try {
    const response = await api.put('/record/submit', {
      aid: parseInt(route.params.id),
      additionInfo: {
        code: inputValue.value
      }
    })

    if (response.data.code === 200) {
      isSubmitted.value = true
      ElMessage.success('签到成功')
      setTimeout(() => {
        router.push(`/${sessionStorage.getItem('jobCode')}/personalPage`)
      }, 1000)
    } else {
      submitError.value = '签到失败，请重试'
      ElMessage.error(submitError.value)
    }
  } catch (error) {
    console.error('提交失败:', error)
    submitError.value = '请求失败，请检查网络'
    ElMessage.error(submitError.value)
  } finally {
    isSubmitting.value = false
  }
}
</script>

<style scoped>
.sign-in-container {
  max-width: 420px;
  margin: 25% auto;
  padding: 30px 20px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.08);
  display: flex;
  flex-direction: column;
  align-items: center;
}

.check-in-form {
  margin-top: 20px;
  width: 100%;
}

.input-group {
  margin-bottom: 20px;
}

.input-field {
  width: 100%;
  padding: 14px 16px;
  font-size: 16px;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  box-sizing: border-box;
  transition: all 0.3s ease;
  text-align: center;
}

.input-field:focus {
  outline: none;
  border-color: #3b82f6;
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}

.error-message {
  color: #e42844;
  font-size: 14px;
  margin-top: 5px;
  text-align: left;
}

.check-in-button {
  width: 100%;
  padding: 14px;
  background: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%);
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  margin-top: 10px;
}

.check-in-button:hover:not(:disabled) {
  background: linear-gradient(135deg, #2563eb 0%, #1d4ed8 100%);
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(59, 130, 246, 0.25);
}

.check-in-button:disabled {
  background: #a5b4fc;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

@media (max-width: 480px) {
  .sign-in-container {
    padding: 20px 15px;
  }
}
</style>